using System;
using System.Collections.Generic;
using System.Text;
using System.Timers;
using log4net;

namespace Sedna.Core.Scheduler.Conditions
{
    public class DailyCondition : BaseCondition
    {
        private ILog log = LogManager.GetLogger(typeof(DailyCondition));

        private DateTime time;
        private Timer timer;
        private int interval = 20000;
        private TimeSpan timeTimeSpan;
        private DateTime? lastRun = null;

        public DailyCondition()
        {
            timer = new Timer();
            timer.Elapsed += new ElapsedEventHandler(OnElapsed);
        }

        # region Properties

        public DateTime Time
        {
            set { time = value; }
        }

        public int Interval
        {
            set { interval = value; }
        }

        # endregion        


        protected override void OnEnable()
        {
            timer.Interval = interval;
            timer.Start();
            timeTimeSpan = time.TimeOfDay;
            log.Info(String.Format("Start time: {0}", time));
        }

        protected override void OnDisable()
        {
            timer.Stop();
        }


        private void OnElapsed(object sender, ElapsedEventArgs e)
        {
            double diff = DateTime.Now.TimeOfDay.Subtract(timeTimeSpan).TotalMilliseconds;
            
            if (diff < 0 || diff > interval)
            {
                return;
            }
            
            if (lastRun != null && (DateTime.Now.Subtract(lastRun.Value).TotalMilliseconds < interval))
            {
                return;
            }
            
            OnTrigger();
        }

    }
}
